﻿using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Win32;

namespace DirMod.ViewModels
{
    public class DirMainViewModel : BindableBase
    {
        public string Title { get; set; } = "DirMod";
        private bool cbExportPath;

        public bool CbExportPath
        {
            get { return cbExportPath; }
            set { SetProperty(ref cbExportPath, value); }
        }
        public DelegateCommand ExportFileNameCommand { get; set; }
        public DirMainViewModel()
        {
            CbExportPath = true;
            ExportFileNameCommand = new DelegateCommand(OnExportFileName);
        }

        private void OnExportFileName()
        {
            var ofd = new OpenFolderDialog();
            ofd.Multiselect = false;
            if (ofd.ShowDialog() == true)
            {
                var selectedDir = ofd.FolderName;
                var names = GetFileNameInDir(selectedDir,CbExportPath);
                var saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "Text files (*.txt)|*.txt";
                if (saveFileDialog.ShowDialog() == true)
                {
                    var saveFile = saveFileDialog.FileName;
                    File.WriteAllLines(saveFile,names.ToArray());
                }
            }
        }

        private List<string> GetFileNameInDir(string path,bool exportPath = false)
        {
            var fileNames = new List<string>();

            var dir = new DirectoryInfo(path);
            if (dir.Exists)
            {
                var files = dir.GetFiles();
                    foreach (FileInfo fileInfo in files)
                    {
                        if (exportPath)
                        {
                            fileNames.Add(fileInfo.FullName);
                        }
                        else
                        {
                            fileNames.Add(fileInfo.Name);
                        }
                    }
                var dirs = dir.GetDirectories();
                foreach (var _dir in dirs)
                {
                  var temps = GetFileNameInDir(_dir.FullName,exportPath);
                  fileNames.AddRange(temps);
                }
            }

            return fileNames;
        }

    }
}
